package com.gbiac.modules.monitor.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dtflys.forest.http.ForestCookie;
import com.gbiac.modules.monitor.constant.MonitorConstant;
import com.gbiac.modules.monitor.entity.PalmVeinRecord;
import com.gbiac.modules.monitor.http.HttpApi;
import com.gbiac.modules.monitor.mapper.PalmVeinRecordMapper;
import com.gbiac.modules.monitor.model.dto.*;
import com.gbiac.modules.monitor.service.IPalmVeinRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description: 掌静脉打卡记录
 * @Author: jeecg-boot
 * @Date:   2024-11-30
 * @Version: V1.0
 */
@Service
@Slf4j
public class PalmVeinRecordServiceImpl extends ServiceImpl<PalmVeinRecordMapper, PalmVeinRecord> implements IPalmVeinRecordService {


    @Resource
    private HttpApi httpApi;
    @Value("${gbiac.monitor.palmVein.password}")
    private String password;

    AtomicReference<ForestCookie> cookieAtomic = new AtomicReference<>(null);

    private static final Integer CONSTANT_STATUS_OK=200;

    private static final String CONSTANT_REDIS_PREFIX= MonitorConstant.REDIS_PREFIX +":"+ "PALMVEIN_SYNCED_USERS_1";
    @Resource
    private RedisUtil redisUtil;
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /**
     * 连接登录掌静脉设备
     */
    public Result<String> loginPalmVeinDevice() {
        PalmVeinDeviceLoginResponseDTO result = httpApi.postPalmVeinLogin(new PalmVeinDeviceLoginParamDTO(password), (request, cookies) -> {
            // 将服务端传来的Cookie放入cookieAtomic
            cookieAtomic.set(cookies.allCookies().get(0));
        });
        if(CONSTANT_STATUS_OK.intValue() == result.getStatus()){
            log.info("===连接掌静脉设备成功,{}",result);
            return Result.ok();
        }else {
            String msg = JSONObject.toJSONString(result);
            log.info("===登录掌静脉设备失败,{}",msg);
            return Result.error("登录掌静脉设备失败："+msg);
        }
    }

    /**
     * 添加单个人员
     */
    @Override
    public Result<String> addPersonPalmVeinDevice(Boolean isLogin, LoginUser sysUser) {
        if(isLogin == true) {
            Result<String> result = loginPalmVeinDevice();
            // 获取Cookie
            ForestCookie cookie = cookieAtomic.get();
            if (!result.isSuccess() || cookie == null) {
                return result;
            }
        }

        String jsonText = (String) redisUtil.get(CONSTANT_REDIS_PREFIX);
        if(jsonText == null){
            jsonText = "{}";
        }
        JSONObject json = JSONObject.parseObject(jsonText);
        String id = sysUser.getId();
        PalmVeinDeviceSyncedUsersDTO palmVeinDeviceSyncedUsersDTO = json.getObject(id,PalmVeinDeviceSyncedUsersDTO.class);
        if(palmVeinDeviceSyncedUsersDTO != null){
            return Result.error("人员已经同步");
        }

        String avatar = sysUser.getAvatar();
        if(StringUtils.isEmpty(avatar)){
            return Result.error("同步失败，人员头像为空");
        }

        String filePath = uploadpath + File.separator + avatar;
        File file = new File(filePath);
        ForestCookie cookie = cookieAtomic.get();
        PalmVeinDeviceUploadImageReponseDTO palmVeinDeviceUploadImageReponseDTO = httpApi.postPalmVeinUploadImage(file,  (request, cookies) -> {
            // 将之前调用登入接口获得的Cookie传入请求发送到服务端
            cookies.addCookie(cookie);
        });
        if(null == palmVeinDeviceUploadImageReponseDTO || CONSTANT_STATUS_OK.intValue() != palmVeinDeviceUploadImageReponseDTO.getStatus() || StringUtils.isEmpty(palmVeinDeviceUploadImageReponseDTO.getEntity())){
            String message = palmVeinDeviceUploadImageReponseDTO.getMessage();
            return Result.error(message);
        }

        PalmVeinDeviceAddPersonParamDTO palmVeinDeviceAddPersonParamDTO = new PalmVeinDeviceAddPersonParamDTO();
        palmVeinDeviceAddPersonParamDTO.setId(sysUser.getId());
        palmVeinDeviceAddPersonParamDTO.setName(sysUser.getRealname());
        palmVeinDeviceAddPersonParamDTO.setIccard(sysUser.getWorkNo());
        palmVeinDeviceAddPersonParamDTO.setJobNo(sysUser.getWorkNo());
        palmVeinDeviceAddPersonParamDTO.setFilePath(palmVeinDeviceUploadImageReponseDTO.getEntity());
        PalmVeinDeviceAddPersonReponseDTO palmVeinDeviceAddPersonReponseDTO = httpApi.postPalmVeinAddPerson(palmVeinDeviceAddPersonParamDTO, (request, cookies) -> {
            // 将之前调用登入接口获得的Cookie传入请求发送到服务端
            cookies.addCookie(cookie);
        });
        if(null == palmVeinDeviceAddPersonReponseDTO || CONSTANT_STATUS_OK.intValue() != palmVeinDeviceAddPersonReponseDTO.getStatus()){
            return Result.error(palmVeinDeviceAddPersonReponseDTO.getMessage());
        }
        json.put(id,new PalmVeinDeviceSyncedUsersDTO(id,palmVeinDeviceAddPersonParamDTO.getName()));
        redisUtil.set(CONSTANT_REDIS_PREFIX,json.toJSONString());
        return Result.ok();
    }
    /**
     * 批量添加人员
     */
    public Result<String> batchAddPersonPalmVeinDevice(List<LoginUser> userList){
        Result<String> result = loginPalmVeinDevice();
        // 获取Cookie
        ForestCookie cookie = cookieAtomic.get();
        if (!result.isSuccess() || cookie == null) {
            return result;
        }
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < userList.size(); i++) {
            LoginUser sysUser = userList.get(i);
            try {
                Result<String> result1 = addPersonPalmVeinDevice(false, sysUser);
                buffer.append("添加(id=").append(sysUser.getId()).append(")结果为:(").append(result1.getMessage()).append(")\n");
            }catch (Exception e){
                log.error(e.getMessage(),e);
                buffer.append("添加(id=").append(sysUser.getId()).append(")异常:(").append(e.getMessage()).append(")\n");
            }
        }
        return Result.ok(buffer.toString());
    }

    @Override
    public Result<String> deletePersonPalmVeinDevice(String id) {
        Result<String> result = loginPalmVeinDevice();
        // 获取Cookie
        ForestCookie cookie = cookieAtomic.get();
        if (!result.isSuccess() || cookie == null) {
            return result;
        }
        PalmVeinDeviceDeleteImageReponseDTO reponseDTO = httpApi.postDeletePersonPalmVeinDevice(id,  (request, cookies) -> {
            // 将之前调用登入接口获得的Cookie传入请求发送到服务端
            cookies.addCookie(cookie);
        });
        if(null == reponseDTO || CONSTANT_STATUS_OK.intValue() != reponseDTO.getStatus()){
            return Result.error(reponseDTO.getMessage());
        }
        return Result.ok();
    }


}
